package com.nl.lib_core.view.selector

/** 作者: wangfei 创建时间: 2021/9/1 包名: com.nl.lib_core.view 类名: LoadingInitView 容器进行管理按钮及当前选中状态 */
class SelectorGroup {
  private var choiceMode: ChoiceAction? = null
  private var onStateChangeListener: StateListener? = null

  private val selectorMap: LinkedHashMap<String?, Selector> = LinkedHashMap()

  fun setChoiceMode(choiceMode: ChoiceAction?) {
    this.choiceMode = choiceMode
  }

  fun setChoiceMode(mode: Int) {
    when (mode) {
      MODE_MULTIPLE_CHOICE -> choiceMode = MultipleAction()
      MODE_SINGLE_CHOICE -> choiceMode = SingleAction()
    }
  }

  fun setStateListener(onStateChangeListener: StateListener?) {
    this.onStateChangeListener = onStateChangeListener
  }

  fun getPreSelector(groupTag: String?): Selector? {
    return selectorMap[groupTag]
  }
  /** 设置选中项 */
  fun setSelected(selected: Boolean, selector: Selector?) {
    if (selector == null) {
      return
    }
    if (selected) {
      selectorMap[selector.groupTag] = selector
    }
    selector.isSelected = selected
    if (onStateChangeListener != null) {
      onStateChangeListener!!.onStateChange(selector.groupTag, selector.selectorTag, selected)
    }
  }
  /** 去掉上一个选中项 */
  private fun cancelPreSelector(selector: Selector) {
    val groupTag = selector.groupTag
    val preSelector = getPreSelector(groupTag)
    if (preSelector != null) {
      preSelector.isSelected = false
    }
  }

  fun onSelectorClick(selector: Selector) {
    if (choiceMode != null) {
      choiceMode!!.onChoose(selector, this, onStateChangeListener)
    }
    // keep click selector in map
    selectorMap[selector.groupTag] = selector
  }

  fun clear() {
    selectorMap.clear()
  }

  interface ChoiceAction {
    fun onChoose(selector: Selector, selectorGroup: SelectorGroup?, stateListener: StateListener?)
  }

  private inner class SingleAction : ChoiceAction {
    override fun onChoose(
        selector: Selector,
        selectorGroup: SelectorGroup?,
        stateListener: StateListener?
    ) {
      cancelPreSelector(selector)
      setSelected(true, selector)
    }
  }

  private inner class MultipleAction : ChoiceAction {
    override fun onChoose(
        selector: Selector,
        selectorGroup: SelectorGroup?,
        stateListener: StateListener?
    ) {
      val isSelected = selector.isSelected
      setSelected(!isSelected, selector)
    }
  }

  interface StateListener {
    /** @param tag 选中选项的index*/
    fun onStateChange(groupTag: String?, tag: String?, isSelected: Boolean)
  }

  companion object {
    const val MODE_SINGLE_CHOICE = 1
    const val MODE_MULTIPLE_CHOICE = 2
  }
}
